/*
 * XMLUtil.java
 */

package xq.util;

/**
 *
 * @author ThorntonRP
 */
public class XMLUtil {

	public static String formatXML(String xml) {
		xml = xml.replace("><", ">\n<");
		String[] lines = xml.split("\n");
		int level = 0;
		String indent = "  ";
		StringBuilder sb = new StringBuilder(xml.length());
		for (String line : lines) {
			if (line.matches("^\\s*<[^/][^>]*?[^/]>\\s*$")) { // opening tag
				appendLine(sb, line.trim(), indent, level);
				level++;
			} else if (line.matches("^\\s*</[^>]*?>\\s*$")) { // closing tag
				level--;
				appendLine(sb, line.trim(), indent, level);
			} else {
				appendLine(sb, line.trim(), indent, level);
			}
		}
		return sb.toString();
	}

	private static void appendLine(StringBuilder sb, String line, String indent, int level) {
		for (int i = 0; i < level; i++) {
			sb.append(indent);
		}
		sb.append(line).append("\n");
	}
	
	private XMLUtil() {}
}
